import AlertDialog from '@/components/AlertDialog';
import PermissionNotGrantedDialog from '@/components/PermissionNotGrantedDialog';
import { TSUN_BLE_CRYPTO_KEYS } from '@/config/config';
import useBleScan from '@/hooks/useBleScan';
import StringUtils from '@/utils/StringUtils';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { Buffer } from 'buffer';
import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  FlatList,
  TouchableOpacity,
  View,
  Text,
  Linking,
  Alert,
} from 'react-native';
import {
  BleScanMatchMode,
  BleScanMode,
  Peripheral,
} from 'react-native-ble-manager';
import { Button, Icon, useAppTheme } from 'tsun-smart-ui';

const DiscoverDevicesScreen: React.FC = () => {
  const {
    startScan,
    peripherals,
    isScanning,
    connectToDevice,
    bluetoothDialogShouldOpen,
    setBluetoothDialogShouldOpen,
    permissionDialogShouldOpen,
    // setPermissionDialogShouldOpen,
  } = useBleScan();
  const { t } = useTranslation();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  /// 是否跳过添加设备，直接去配网，作为配网工具模式下使用
  const setupNetworkOnly = route.params?.setupNetworkOnly ?? false;
  const appTheme = useAppTheme();

  useEffect(() => {
    onRefresh();
    navigation.setOptions({
      headerRight: () => (
        <View >
          <TouchableOpacity onPress={onRefresh}>
            <Icon
              name="refresh"
              size={24}
              color={appTheme.colors?.neutral?.title}
            />
          </TouchableOpacity>
        </View>
      ),
    });
  }, []);

  const onRefresh = useCallback(() => {
    startScan([], 15, false, {
      scanMode: BleScanMode.LowPower,
    });
  }, []);

  useEffect(() => {
    if (permissionDialogShouldOpen) {
      Alert.alert(t('message.enablePermission'), undefined, [
        {
          text: t('user.logOutCancel'),
        },
        {
          text: t('common.confirmButtonText'),
          onPress: Linking.openSettings,
        },
      ]);
    }
  }, [permissionDialogShouldOpen]);

  const renderListHeader = useCallback(() => {
    return (
      <Text className="mb-3 text-text2">{t('sys.app.discover.devices')}</Text>
    );
  }, []);
  const renderItem = useCallback(
    ({ item, index }: { item: Peripheral; index: number }) => {
      const deviceDisplayName =
        item.name ?? item.advertising.localName ?? item.id;
      const isFirstOne = index === 0;
      const isLastOne = index === peripherals.length - 1;
      const topBorderRadius = 'rounded-tl-lg rounded-tr-lg';
      const bottomBorderRadius = 'rounded-bl-lg rounded-br-lg';
      const borderRadius = `${isFirstOne ? topBorderRadius : ''} ${
        isLastOne ? bottomBorderRadius : ''
      }`;
      return (
        <View
          className={`items-center px-3 flex-row gap-2 py-3 bg-text6 ${borderRadius}`}
        >
          <Text className="text-text1 text-[15px] font-medium shrink">
            {deviceDisplayName}
          </Text>
          <View className="grow" />

          <TouchableOpacity
            className="bg-brand4 px-5 py-2 rounded-full text-[14px]"
            onPress={async () => {
              if (setupNetworkOnly) {
                navigation.navigate('SetupDeviceNetwork', {
                  snCode: deviceDisplayName,
                });
              } else {
                navigation.navigate('SNCode', {
                  code: deviceDisplayName,
                  station: route.params?.station,
                  category: route.params?.category,
                });
              }
            }}
          >
            <Text className="text-brand1 text-[14px] leading-[14px] font-medium">
              {t('sys.common.add')}
            </Text>
          </TouchableOpacity>
        </View>
      );
    },
    [peripherals, setupNetworkOnly]
  );

  const renderListFooter = useCallback(() => {
    return (
      <View className="items-stretch mb-8 mt-3">
        {isScanning && <ActivityIndicator color={appTheme.colors?.brand?.onPrimary} />}
        <Text className="text-text3 leading-5">
          {t('sys.app.if.cannot.find.device')}
        </Text>
      </View>
    );
  }, [isScanning, t]);

  return (
    <>
      <FlatList
        className="flex-1"
        contentContainerClassName="px-3 py-3"
        data={peripherals}
        renderItem={renderItem}
        ItemSeparatorComponent={ItemSeparator}
        ListHeaderComponent={renderListHeader}
        ListFooterComponent={renderListFooter}
        keyExtractor={(item) => item.id}
      />
      <AlertDialog
        visible={bluetoothDialogShouldOpen}
        onDismiss={() => setBluetoothDialogShouldOpen(false)}
        title={t('sys.app.open.ble')}
        subtitle={t('sys.app.open.ble.detail')}
        buttons={[
          {
            title: t('user.logOutCancel'),
            onPress: () => {
              /// 蓝牙没开启，又点了取消
            },
          },
          {
            title: t('common.confirmButtonText'),
            highlighted: true,
            onPress: () => {},
          },
        ]}
      />
      {/* <PermissionNotGrantedDialog
        visible={permissionDialogShouldOpen}
        onDismiss={() => setPermissionDialogShouldOpen(false)}
      /> */}
    </>
  );
};

export default React.memo(DiscoverDevicesScreen);

const ItemSeparator = React.memo(() => {
  return <View className="bg-line1 h-[1px] mx-4" />;
});

const IconButton = React.memo(
  (props: { iconName: string; title: string; onPress: () => void }) => {
    const appTheme = useAppTheme();
    return (
      <TouchableOpacity
        className="flex-row items-center justify-center gap-2 rounded-md bg-text6 flex-1 py-4"
        onPress={props.onPress}
      >
        <Icon
          name={props.iconName}
          size={18}
          color={appTheme.colors?.brand?.primary}
        />
        <Text className="text-text1 font-medium">{props.title}</Text>
      </TouchableOpacity>
    );
  }
);
